package com.java.controller;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;

@Controller
public class ShowUsernameController {

    @RequestMapping("/showUsername")
    public void showUsername(HttpServletRequest request) {
        // 获取session对象
        HttpSession session = request.getSession();
        // 从session域中获取登陆信息
        // 枚举类型：遍历枚举类型
        Enumeration attributeNames = session.getAttributeNames();
        while (attributeNames.hasMoreElements()) { // 判断是否有更多的元素
            System.out.println(attributeNames.nextElement());   // 获取下一个元素
        }
        // SPRING_SECURITY_CONTEXT 存储用户登陆信息的session中的名称
        Object spring_security_context = session.getAttribute("SPRING_SECURITY_CONTEXT");
        // 获取的时SecurityContext对象，是安全框架的上下文对象
        SecurityContext securityContext = (SecurityContext) spring_security_context;
        System.out.println(securityContext);

        // 获取认证信息
        Authentication authentication = securityContext.getAuthentication();
        // 用户对象
        UserDetails user = (UserDetails) authentication.getPrincipal();
        System.out.println("用户名：" + user.getUsername());


        // 获取上下文对象方法二
        SecurityContext context = SecurityContextHolder.getContext();
        System.out.println(context == securityContext);
    }
}
